package com.chj.comp.common.rabbitmq.queue;

import com.chj.comp.common.rabbitmq.sender.MqDirectSender;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 *
 * @Description: 发布订阅模型（Direct路由类型，一个消息被某些消费者消费）：
 * 发送消息时指定路由，交换机会将接收到的消息根据规则路由到指定的queue
 *
 *                            / 队列1（绑定路由） - 消费者1
 * 生产者（指定路由） - 交换机
 *                           \ 队列2（绑定路由） - 消费者2
 *
 * @author cuihui
 * @date 2022-06-11
 *
 */
@Configuration
public class MqDirectQueue {
    @Resource
    private RabbitTemplate rabbitTemplate;

    public static final String EXCHANGE_NAME = "mq.direct.exchange";
    public static final String QUEUE_NAME1 = "mq.direct.queue1";
    public static final String ROUTING_KEY1 = "mq.routing.key1";
    public static final String QUEUE_NAME2 = "mq.direct.queue2";
    public static final String ROUTING_KEY2 = "mq.routing.key2";

    /**
     * 定义交换机
     * @return
     */
    @Bean
    public DirectExchange mqDirectExchange() {
        return ExchangeBuilder.directExchange(EXCHANGE_NAME).build();
    }

    /**
     * 定义队列1
     * @return
     */
    @Bean
    public Queue mqDirectQueue1() {
        return QueueBuilder.durable(QUEUE_NAME1).build();
    }

    /**
     * 定义队列2
     * @return
     */
    @Bean
    public Queue mqDirectQueue2() {
        return QueueBuilder.durable(QUEUE_NAME2).build();
    }

    /**
     * 绑定队列1到交换机
     * @return
     */
    @Bean
    public Binding mqDirectQueue1Binding() {
        return BindingBuilder
                .bind(mqDirectQueue1())
                .to(mqDirectExchange())
                // 队列绑定至交换机并指定路由（精确匹配）
                .with(ROUTING_KEY1);
    }

    /**
     * 绑定队列2到交换机
     * @return
     */
    @Bean
    public Binding mqDirectQueue2Binding() {
        return BindingBuilder
                .bind(mqDirectQueue2())
                .to(mqDirectExchange())
                // 队列绑定至交换机并指定路由（精确匹配）
                .with(ROUTING_KEY2);
    }

    @Bean
    public MqDirectSender mqDirectSender() {
        return new MqDirectSender(rabbitTemplate);
    }
}
